package com.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.pojo.Item;
import com.pojo.ItemsQueryVo;
import com.pojo.Page;
import com.service.ItemService;

@Controller
@RequestMapping("/ITEM")
public class ItemController {
	@Autowired
	ItemService service;

	@RequestMapping("/LIST")
	public String itemListController(/* @RequestParam("limit") */Integer limit,
	/* @RequestParam("offset") */Integer offset, Model model) throws Exception {
		Map<String, Object> resultMap = service.getItemList(new Page(limit,
				offset));
		model.addAllAttributes(resultMap);
		return "item/itemlist";
	}

	@RequestMapping("/LIST/DELETE/ALL")
	public String deleteItemList(Integer[] items_id) {
		System.out.println(items_id);
		return "redirect:/ITEM/LIST?offset=0&limit=10";
	}

	@RequestMapping("/EDIT/{itemId}")
	public String editItemConteoller(@PathVariable Integer itemId, Model model)
			throws Exception {
		model.addAttribute("item", service.getItem(itemId));
		return "item/edit";
	}

	@RequestMapping("/EDIT/{itemId}/PUT")
	public String submitItemEdit(@PathVariable Integer itemId,@RequestParam("itemPic")MultipartFile itemPic,Item item,HttpServletRequest request)
			throws Exception {
		service.saveItemPicture(item, itemPic,request.getSession().getServletContext().getRealPath("/"));
		return "redirect:/ITEM/LIST?offset=0&limit=10";
	}

	@RequestMapping(value = "/EDIT/ALL", method = RequestMethod.POST)
	public String getItemList(Integer[] items_id, Model model) throws Exception {
		List<Item> itemsList = new ArrayList<Item>();
		for (Integer id : items_id) {
			itemsList.add(service.getItem(id));
		}
		model.addAttribute("itemsList", itemsList);
		return "item/editall";
	}

	@RequestMapping(value = "/EDIT/ALL/PUT", method = RequestMethod.POST)
	public String submitItemListModify(ItemsQueryVo itemsQueryVo)
			throws Exception {
		for (Item item : itemsQueryVo.getItemsList()) {
			System.out.println(item);
		}
		return "redirect:/ITEM/LIST?offset=0&limit=10";
	}
}
